from json import JSONDecodeError
from html.parser import HTMLParser
from django.shortcuts import render
from xml.sax.saxutils import unescape
# Create your views here.
from django.http import HttpResponse
from DjangoWeb.spider.api.query import querygrade
from DjangoWeb.spider.previousQuery import queryGrade
from DjangoWeb.xxqg.query import search
seaNum = [448962]

def index(request):
    return render(request, 'index.html')


def login(request):
    return render(request, 'login.html')


def query(request):
    import requests
    import json
    api_request = requests.get(url='https://api.github.com/users?since=0')
    user_api = json.loads(api_request.content)
    return render(request, 'query.html', {"api": user_api})


def user(request):
    if request.method == 'POST':
        key_word = request.POST['user']
        if key_word is not None:
            answer_context = search(key_word)
            return render(request, "XxqgResult.html", {"answer_context": answer_context})
        elif key_word == '':
            return render(request, 'login.html', {'msg': '请在搜索框中输入您需要查询的信息!'})
    else:
        return HttpResponse('方法错误')


def grade(request):
    if request.method == 'POST':
        username = request.POST['username']
        password = request.POST['password']
        numid = request.POST['numid']
        inputYear = request.POST['inputYear']
        inputSemester = request.POST['inputSemester']
        if numid == '新系统':
            try:
                api = querygrade(username, password,inputYear,inputSemester)
                if api == '':
                    return render(request, 'login.html', {'msg': '邮箱或者密码有误，请重试！'})
                else:
                    return render(request, 'grade1.html', {'api': api, 'username': username, 'password': password, 'numid':numid})
            except IndexError:
                return render(request, 'login.html', {'msg': '邮箱或者密码有误，请重试！'})
        elif numid == '旧系统':
            try:
                api = unescape(queryGrade.querygrade(username, password))
                # api = unescape('&lt;a name=&quot;2018-2019学年第一学期(两学期)&quot; /&gt;1232&lt;/a&gt;<p>123</p>')
                return render(request,'grade2.html', {'api':api})
            except IndexError:
                return render(request, 'login.html', {'msg': '邮箱或者密码有误，请重试！'})
    else:
        return HttpResponse('方法错误')


def XxqgSearch(request):
    return render(request, 'XxqgSearch.html')

def XxqgResult(request):
    if request.method == 'POST':
        key_word = request.POST['keyword']
        answer_context = search(key_word)
        return render(request, "XxqgResult.html", {"answer_context": answer_context})
    else:
        notfound = "请在搜索框中输入您需要查询的信息"
        return render(request, 'XxqgSearch.html')